package com.princess.demok.ui.demo

import android.app.Activity
import android.content.Intent
import com.princess.demok.R
import com.princess.demok.base.view.MyBaseActivity
import kotlinx.coroutines.*
import java.util.concurrent.atomic.AtomicInteger
import kotlin.system.measureTimeMillis

/**
 * @author: xha
 * @date: 2021/1/20 16:50
 * @Description:
 */
class DemoAsyncActivity : MyBaseActivity() {

    companion object {
        @JvmStatic
        fun start(
            context: Activity
        ) {
            val starter = Intent(context, DemoAsyncActivity::class.java)
            context.startActivity(starter)
        }
    }
    override fun getLayoutId(): Int? {
        return R.layout.activity_compress
    }

    override fun initOnCreate() {
        runBlocking {
            withContext(Dispatchers.Default) {
                massiveRun {
                    counter.incrementAndGet()
                }
            }
            println("Counter = $counter")
        }
    }

    var counter = AtomicInteger()

    suspend fun massiveRun(action: suspend () -> Unit) {
        val n = 100  // number of coroutines to launch
        val k = 1000 // times an action is repeated by each coroutine
        val time = measureTimeMillis {
            coroutineScope { // scope for coroutines
                repeat(n) {
                    launch {
                        repeat(k) { action() }
                    }
                }
            }
        }
        println("Completed ${n * k} actions in $time ms")
    }

}